<template>
	<view class="">
		<view class="wrap">
			<web-view ref="wb" v-if="processInstanceId" :update-title="false" :webview-styles="webviewStyles" :src="webViewUrl" @load="loadWeb" @message="handlePostMessage"></web-view>
			<view class="" style="margin-top: 500px;">
				<u-button type="primary" style="margin-top: 10rpx;" v-if="!disabled && (bpmnType === 'claim' || bpmnType === 'handling') && viewLoaded" @click="handleComplete" >同意</u-button>
				<!-- <u-button type="error" style="margin-top: 10rpx;" v-if="!disabled && bpmnType === 'handling' && viewLoaded" @click="handleRejectLast" >驳回上一节点</u-button> -->
				<u-button type="error" style="margin-top: 10rpx;" v-if="!disabled && (bpmnType === 'claim' || bpmnType === 'handling') && viewLoaded" @click="handleRejectFirst" >不同意</u-button>
				<u-button type="warning" style="margin-top: 10rpx;" v-if="!disabled && (bpmnType === 'claim' || bpmnType === 'handling') && viewLoaded" @click="handleDelegate" >委派</u-button>
				<!-- <u-button type="warning" style="margin-top: 10rpx;" v-if="!disabled && bpmnType === 'claim'&& viewLoaded" @click="handleClaim" >拾取</u-button> -->
				<u-button type="warning" style="margin-top: 10rpx;" v-if="!disabled && bpmnType === 'apply'&& viewLoaded" @click="handleTaskCancel" >撤回</u-button>
				<u-button type="warning" style="margin-top: 10rpx;" v-if="!disabled && bpmnType === 'apply'&& viewLoaded" @click="handleUrgent" >加急</u-button>
				<u-button style="margin-top: 10rpx;"  @click="schedule">流程图</u-button>
				<u-button style="margin-top: 10rpx;margin-bottom: 10rpx;" @click="history">办理记录</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import { postAction,putAction,getAction } from '@/api/manage.js'
	import { CURY_TYPE } from '@/utils/constant.js'
	import navbar from '@/components/navbar.vue'
	import Criteria from '@/utils/criteria'
	import { OPERATOR } from '@/utils/constant'
	import configService from '@/config.js'
	import { mapGetters } from 'vuex'
	export default {
		components:{ navbar },
		data() {
			return {
				urlObj:{
					complete: '/camunda/task/complete/', // 审核通过
					claim: '/camunda/task/claim/', // 拾取
					flowDef: '/camunda/process/details/',
					urgent: '/camunda/process/urgent/',
					cancel: '/camunda/process/cancel/',
					task: '/camunda/task/all/page'// 当前节点任务详情
				},
				disabled:true,
				loading:false,
				processInstanceId:'',
				id:'',
				show:false,
				configService:configService,
				currentWebview:'',
				bpmnType:'',
				task:{}, //节点任务详情
				viewLoaded:false
			}
		},
		computed:{
			...mapGetters(['token','refreshToken']),
			webViewUrl(){
				return configService.pcUrl+'/formView?processInstanceId='+this.processInstanceId+'&id='+this.id+'&bpmnType='+this.bpmnType+'&key='+new Date().getTime()
			},
			webviewStyles(){
				return {
					progress: {
						color: '#FF3333',
					},
					height:this.show?'10px':'500px'
				}
			}
		},
		methods: {
			schedule(row){
				this.$Router.push({
					path:'/pages/flow/bpmnView',
					query:{
						processInstanceId:this.processInstanceId
					}
				})
			},
			async handleComplete(){ //点击同意
				uni.showModal({
					title: '确认',
					content: '是否同意该任务？',
					showCancel: true,
					success: async(res) => {
						if (res.confirm) {
							this.loading = true
							if(this.task.hasForm){
								this.curWebview = this.$scope.$getAppWebview().children()[0]
								
								// 校验节点表单
								this.curWebview.evalJS(`getData()`)
							}else{
								this.complete()
							}
						}
					}
				});
			},
			async complete(data){
				if(this.bpmnType === 'claim'){
					const res = await postAction(this.urlObj.claim+this.id)
				}
				console.log(this.bpmnType)
				const res = await postAction(this.urlObj.complete+this.id,data || {})
				if(res.data.success){
					this.$modal.msgSuccess('操作成功')
					if (res.data.result.state === 'COMPLETED') {
						this.updateBpmnStatus('COMPLETED')
					}
					setTimeout(() => {		
						this.$Router.back()
					},1000)
				}
			},
			handlePostMessage(data){ //接收web-view信息
				const type = data.detail.data[0]?.type
				if(type === 'completed'){ //完成事件
					this.complete(data.detail.data[0].data)
				}else if(type === 'loaded'){
					this.viewLoaded = true
				}
			},
			handleRejectLast(){ //驳回上一节点
				this.curWebview = this.$scope.$getAppWebview().children()[0]
				this.$Router.push({
					path:'/pages/flow/comment',
					query:{
						id:this.id,
						type:'rejectLast',
						viewId:this.curWebview.id
					}
				})
			},
			handleRejectFirst(){ //不同意
				this.curWebview = this.$scope.$getAppWebview().children()[0]
				this.$Router.push({
					path:'/pages/flow/comment',
					query:{
						id:this.id,
						type:'rejectFirst',
						viewId:this.curWebview.id,
						bpmnType:this.bpmnType
					}
				})
			},
			handleDelegate(){ //委派
				this.$Router.push({
					path:'/pages/flow/delegate',
					query:{
						id:this.id
					}
				})
			},
			handleClaim(){ //拾取
				uni.showModal({
				  title: '确认',
				  content: '是否拾取该任务？',
				  showCancel: true,
				  success: res => {
				    if (res.confirm) {
				      this.claim()
				    }
				  }
				});
			},
			claim(){
				this.loading = true
				 postAction(this.urlObj.claim+this.id).then(res => {
					if(res.data.success){
						// this.bpmnType = 'handling'
						setTimeout(() => {		
							this.$Router.back()
						},1000)
					}
				})
			},
			history(){ //审批历史
				this.$Router.push({
					path:'/pages/flow/historyList',
					query:{
						id:this.id,
						processInstanceId:this.processInstanceId
					}
				})
			},
			updateBpmnStatus(state) { // 自定义业务表单 ，签核完成后，更新业务单据流程状态
				this.curWebview = this.$scope.$getAppWebview().children()[0]
				const data = {state:state}
				this.curWebview.evalJS(`updateBpmnStatus(${JSON.stringify(data)})`)
			},
			// async getflowForm() { // 根据流程定义id获取绑定表单-发起单据及流程
			// 	try {
			// 		this.confirmLoading = true
			// 		const res = await getAction(this.urlObj.flowDef + this.processInstanceId)
			// 		if (!res.success) {
			// 			this.confirmLoading = false
			// 			return this.$message.warning('未查询到发起表单')
			// 		}
			// 		this.formData = res.result.startDatas
			// 		this.confirmLoading = false
			// 	} catch (error) {
			// 		this.confirmLoading = false
			// 	}
			// },
			async getTask() { // 获取当前节点任务详情
				const params = this.getQueryParams()
				const {data} = await getAction(this.urlObj.task, params)
				if (data.success) {
					this.task = data.result.content[0]
				}
			},
			getQueryParams() { // 获取查询条件
				const queryParam = new Criteria()
				queryParam.addCriterions({ id: this.id }, OPERATOR.EQ)// 过滤参数转换为jpa支持格式
				var param = Object.assign({}, { criteria: queryParam.getEncode() })
				return param
			},
			// handleMessage(){//设置pc端token
			// 	this.curWebview = this.$scope.$getAppWebview().children()[0]
			// 	const data = {
			// 		refreshToken:this.refreshToken,
			// 		token:this.token
			// 	}
			// 	this.curWebview.evalJS(`updateToken(${JSON.stringify(data)})`)
			// },
			handleTaskCancel(){ //撤回
				this.loading = true
				getAction(this.urlObj.cancel+this.id).then(res => {
					if(res.data.success){
						this.$modal.msgSuccess('操作成功')
						this.updateBpmnStatus('INTERNALLY_CANCEL')
						setTimeout(() => {		
							this.$Router.back()
						},1000)
					}
				})
			},
			handleUrgent(){ //加急
				this.loading = true
				putAction(this.urlObj.urgent+this.id).then(res => {
					if(res.data.success){
						this.$modal.msgSuccess('操作成功')
						setTimeout(() => {		
							this.$Router.back()
						},1000)
					}
				})
			},
			loadWeb(){
				console.log('00000000000')
			}
		},
		onLoad(options) {
			const { id,processInstanceId,disabled,type } = this.$Route.query
			this.id = id
			this.processInstanceId = processInstanceId
			this.disabled = !!disabled
			this.bpmnType = type
			this.getTask()
			uni.setNavigationBarTitle({
			  title: '任务详情'
			})
			// const wv = plus.webview.create("","custom-webview",{
			//       // 'uni-app': 'none', //不加载uni-app渲染层框架，避免样式冲突
			// 			top:uni.getSystemInfoSync().statusBarHeight+44, //放置在titleNView下方。如果还想在webview上方加个地址栏的什么的，可以继续降低TOP值
			// 			...this.webviewStyles
			// 		})
			// 		wv.loadURL(this.webViewUrl)
			// 		var currentWebview = this.$scope.$getAppWebview(); //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
			// 		currentWebview.append(wv);//一定要append到当前的页面里！！！才能跟随当前页面一起做动画，一起关闭
			
		},
		beforeDestroy(){
			this.processInstanceId = false
		}
	}
</script>
<style lang="scss" scoped>
	page {
		background-color: #ffffff;
		padding-left: 10px;
		padding-right: 10px;
	}
	.wrap{
		padding: 12px;
		.form-warp{
			width: 100%;
			height: calc( 100vh - 270px);
		}
	}
</style>
